import { ref } from 'vue';
import { PAGE, POST, PUT } from '@/api/http.js';
import { copy, isNil, round } from '@/api/util.js';
import { getUserInfo } from '@/utils/auth';
import dayjs from 'dayjs';
import { getCurrentInstance } from 'vue';
const instance = getCurrentInstance();

export const shopCartRef = ref([]);
export const shopConsumeRef = ref([]);
export const cardMoneyRef = ref([]);
export const beauticianRef = ref([]);
export const cartTypeRef = ref(null);

// 升级操作的卡
const quoteCard = ref({});

export const cartInfoRef = ref({
  //优惠金额
  discountAmount: 0,
});

export function updateQuoteCard(info) {
  quoteCard.value = info;
}

/**
 * 加载挂单数据
 */
export async function loadPendingData(state) {
  const { takeId, workDate } = state;
  const { list } =
    (await PAGE('/cashier/getPendingOrder')({
      id: takeId,
      workDate,
      currentPage: 1,
      pageSize: 999999,
    })) ?? {};

  const target = list?.[0];
  const pendingData = target ? JSON.parse(target?.pendingData || emptyPendingData) : null;

  shopCartRef.value = pendingData?.shopCart ?? [];
  shopConsumeRef.value = pendingData?.shopConsume ?? [];

  const cartInfo = pendingData?.cartInfo ?? {};
  cartInfo.addTime = dayjs(cartInfo.addTime);
  cartInfoRef.value = cartInfo;

  if (!target) {
    state.takeId = null;
    state.workDate = null;
  }
}

export function initCart(cartType) {
  cartTypeRef.value = cartType;
  clearCart();

  return {
    shopCartRef,
    cardMoneyRef,
    shopConsumeRef,
    cartInfoRef,
    beauticianRef,
  };
}

export function clearCart() {
  shopCartRef.value = [];
  cardMoneyRef.value = [];
  shopConsumeRef.value = [];
  cartInfoRef.value = { addTime: dayjs() };
}

export function addCardGoods2Cart(data) {
  const { cardTimesPackItem, cardTimesGoodsItem } = data;
  // console.log(cardTimesPackItem,cardTimesGoodsItem)
  const cateType = 'V';
  const busType = 'goods';

  // 取自 getUserCardList接口的 cardTimesPack.cardTimesGoodsList.salePrice
  const salePrice = cardTimesGoodsItem.salePrice ?? 0;
  const cardSubType = cardTimesPackItem.cardSubType;
  const busParentId = cardTimesPackItem.id;
  const busId = cardTimesGoodsItem.id;

  const parentTitle = cardTimesPackItem.cardName;
  const title = cardTimesGoodsItem.goodsName;

  // 取自 getUserCardList接口的 cardTimesPack.cardTimesGoodsList.averagePrice
  const averagePrice = cardTimesGoodsItem?.averagePrice;

  /**
   * 可能需要选择不同老师，所以需要新增一条记录
   */
  const item = {
    cateType,
    busType,
    cardSubType,
    busParentId,
    busId,
    parentTitle,
    title,
    qty: 0,
    unitPrice: salePrice,
    averagePrice,
    disabledGive: true,
    isGive: false,
    primitive: { cardTimesPackItem, cardTimesGoodsItem },
    beauticianList: [],
  };

  item.id ||= new Date().getTime().toString();

  const remainQty = getCardGoodsRemainQty({ cardTimesPackItem, cardTimesGoodsItem });
  if (remainQty > 0) {
    item.qty += 1;
  }

  let goodsList = shopCartRef.value;

  goodsList.push(item);

  shopCartRef.value = copy(goodsList);

  // shopCartRef.value.push(item);
  /* if (index > -1) {
    shopCartRef.value[index] = { ...item };
  } else {
    shopCartRef.value.push(item);
  } */

  calcPriceByCart();
  addShopConsume('C', data);
}

export function getCardGoodsRemainQty({ cardTimesPackItem, cardTimesGoodsItem }) {
  const cateType = 'V';
  const busType = 'goods';

  const cardSubType = cardTimesPackItem.cardSubType;
  const busParentId = cardTimesPackItem.id;

  if (cardSubType === '201') {
    const busId = cardTimesGoodsItem.id;

    //有限次卡
    const used = shopCartRef.value
      .filter(
        (o) =>
          o.cateType === cateType &&
          o.busType === busType &&
          o.busParentId === busParentId &&
          o.busId === busId,
      )
      .reduce((pv, cv) => pv + (cv.qty || 0), 0);
    return (cardTimesGoodsItem.qty || 0) - used;
  } else if (cardSubType === '202') {
    //不限次卡
    return 999999;
  } else if (cardSubType === '203') {
    //通卡
    const used = shopCartRef.value
      .filter(
        (o) => o.cateType === cateType && o.busType === busType && o.busParentId === busParentId,
      )
      .reduce((pv, cv) => pv + (cv.qty || 0), 0);

    return (cardTimesPackItem.remainQty || 0) - used;
  }

  return -1;
}

export function addCardGive2Cart({ cardTimesPackItem, memberBenefitsBeanItem }) {
  const cateType = 'V';
  const busType = 'give';

  const cardSubType = cardTimesPackItem.cardSubType;
  const busParentId = cardTimesPackItem.id;
  const busId = memberBenefitsBeanItem.id;

  const parentTitle = cardTimesPackItem.cardName;
  const title = memberBenefitsBeanItem.benefitsName;

  const { benefitsType, productSalePrice, serviceSalePrice, cardSalePrice } =
    memberBenefitsBeanItem || {};

  // 赠品原价取不同字段
  const priceObj = {
    P: productSalePrice,
    S: serviceSalePrice,
    C: cardSalePrice,
  };

  const salePrice = priceObj[benefitsType] ?? 0;

  // const index = shopCartRef.value.findIndex(
  //   (o) =>
  //     o.cateType === cateType &&
  //     o.busType === busType &&
  //     o.busParentId === busParentId &&
  //     o.busId === busId,
  // );
  const item =
    // index > -1
    //   ? shopCartRef.value[index]
    //   :
    {
      unitPrice: salePrice,
      cateType,
      busType,
      cardSubType,
      busParentId,
      busId,
      parentTitle,
      title,
      qty: 0,
      disabledGive: true,
      isGive: true,
      primitive: { cardTimesPackItem, memberBenefitsBeanItem },
      beauticianList: [],
    };

  item.id ||= new Date().getTime().toString();

  const remainQty = getCardGiveRemainQty({ cardTimesPackItem, memberBenefitsBeanItem });
  if (remainQty > 0) {
    item.qty = 1;
  }

  let givesList = shopCartRef.value;

  // if (index === -1) {
  givesList.push(item);
  // }

  shopCartRef.value = copy(givesList);

  // shopCartRef.value.push(item);

  /* if (index > -1) {
    shopCartRef.value[index] = { ...item };
  } else {
    shopCartRef.value.push(item);
  } */

  calcPriceByCart();
}

export function getCardGiveRemainQty({ cardTimesPackItem, memberBenefitsBeanItem, cartItem }) {
  const cateType = 'V';
  const busType = 'give';

  const busParentId = cardTimesPackItem.id;
  const busId = memberBenefitsBeanItem.id;

  const used = shopCartRef.value
    .filter(
      (o) =>
        o.cateType === cateType &&
        o.busType === busType &&
        o.busParentId === busParentId &&
        o.busId === busId &&
        (!cartItem || o.id === cartItem.id),
    )
    .reduce((pv, cv) => pv + (cv.qty || 0), 0);

  return (memberBenefitsBeanItem.benefitsQty || 0) - used;
}

export function onAddProduct2Cart(cateType, proItem, options = {}) {
  const busId = proItem.id;
  const title = proItem.goodsName || proItem.cardName;
  let unitPrice = 0;

  if (cateType === 'P' || cateType === 'S') {
    unitPrice = proItem.salePrice;
  } else if (cateType === 'C') {
    unitPrice = proItem.salePrice;
  }

  unitPrice ||= 0;
  unitPrice = round(unitPrice);

  if (cartTypeRef.value === 'cardUpgrade') {
    //卡升级
    if (
      shopCartRef.value.length > 0 &&
      shopCartRef.value[0]?.primitive?.proItem?.goodsSn !== proItem.goodsSn
    ) {
      shopCartRef.value = [];
    }

    const item = shopCartRef.value.find((o) => o.cateType === cateType && o.busId === busId);
    if (!!item) {
      item.qty++;
      return;
    }
  }

  const item = {
    cateType,
    busId,
    title,
    unitPrice,
    // 商品数量
    qty: 1,
    // 禁用赠送权益， 选择客户权益时为true
    disabledGive: false,
    // 设置为赠送权益
    isGive: false,
    primitive: { proItem },
    cardMoneyId: null,
    beauticianList: [],
  };

  /**
   * 使用默认卡耗
   *
   * 金额卡不可使用
   * */
  if (options.cardMoneyId && proItem.cardType !== '100') {
    item.cardMoneyId = parseInt(options.cardMoneyId);
  }

  item.id ||= new Date().getTime().toString();

  const datalist = shopCartRef.value;
  datalist.push(item);
  console.log(datalist);
  shopCartRef.value = copy(datalist);

  calcPriceByCart(item);
  addShopConsume('P', item);
}

export function isExistProductByCart(cateType, proItem) {
  return (
    shopCartRef.value?.findIndex(
      (o) => o.cateType === cateType && (!proItem || o.busId === proItem.id),
    ) > -1
  );
}

export function isExistByCart(cateType) {
  return shopCartRef.value?.findIndex((o) => o.cateType === cateType) > -1;
}

export function onToggleGive(cartItem, isGive) {
  calcPriceByCart();
}

export function selectByCart(item, $event, index) {
  console.log(item, $event, index);
  shopCartRef.value[index].beauticianList = copy($event);
  console.log(shopCartRef.value[index], 78909878);
}

export async function onDeleteConsume(item) {
  const index = shopConsumeRef.value?.findIndex((o) => o.goodsSn === item.goodsSn);
  if (index > -1) {
    const list = copy(shopConsumeRef.value);
    list.splice(index, 1);
    shopConsumeRef.value = list;
  }
}

export function onConsumeComplete(data) {
  if (data.deleteIds.length) {
    data.deleteIds.forEach((sn) => {
      onDeleteConsume({ goodsSn: sn });
    });
  }
  if (data.newData.length) {
    const list = copy(shopConsumeRef.value);
    list.push(...data.newData);
    shopConsumeRef.value = list;
  }
  console.log(shopConsumeRef.value, 'onConsumeComplete');
}

// 配料丢弃
export function deleteShopConsume(cartItem) {
  console.log(cartItem, shopConsumeRef.value, 'deleteShopConsume');
  let consumeList = [];
  if (cartItem.cateType === 'V') {
    consumeList = cartItem.primitive?.cardTimesGoodsItem?.consumeList || [];
  } else {
    consumeList = cartItem.primitive?.proItem?.consumeList || [];
  }
  // 拿到当前商品的配料
  consumeList.forEach((item) => {
    // 看是否存在,有可能被单独删除了
    const index = shopConsumeRef.value?.findIndex((o) => o.goodsSn === item.productGoodsSn);
    if (index > -1) {
      // 如果被添加次数大于1，说明还有被其他商品使用用，不能删。
      if (shopConsumeRef.value[index].linkNum > 1) {
        shopConsumeRef.value[index].linkNum--;
      } else {
        shopConsumeRef.value.splice(index, 1);
      }
    }
  });
  // 如果商品都删完了，则剩下的手动添加的配料都清空
  if (!shopCartRef.value.length) {
    shopConsumeRef.value = [];
  }
}
//配料收集
export function addShopConsume(type, data) {
  console.log('addShopConsume:', type, data);
  const shopConsumeList = [];
  let consumeList = [];
  if (type === 'P') {
    consumeList = data.primitive?.proItem?.consumeList || [];
  } else if (type === 'C') {
    consumeList = data.cardTimesGoodsItem?.consumeList || [];
  }
  consumeList?.forEach((c) => {
    const { productGoodsSn: goodsSn, productGoodsName: goodsName } = c;
    const index = shopConsumeRef.value?.findIndex((z) => z.goodsSn === goodsSn);
    // 如果已经存在，linkNum+1，默认值为1
    if (index < 0) {
      shopConsumeList.push({ ...c, csmValue: null, goodsSn, goodsName, linkNum: 1 });
    } else {
      shopConsumeRef.value[index].linkNum++;
    }
  });
  shopConsumeRef.value = [...shopConsumeRef.value, ...copy(shopConsumeList)];
  console.log(shopConsumeRef.value, shopCartRef.value, 'shopConsumeRef-shopConsumeRef');
}

export function calcPriceByCart() {
  // 不限次卡的金额需要实时计算，在此初始化剩余金额
  const infiniteCardAmount = {};

  shopCartRef.value?.forEach((cartItem) => {
    if (cartItem?.primitive?.cardTimesPackItem) {
      infiniteCardAmount[cartItem.busParentId] =
        cartItem?.primitive?.cardTimesPackItem?.remainAmount || 0;
    }
  });

  //初始化
  shopCartRef.value?.forEach((cartItem) => {
    console.log(cartItem, 'cartItem');
    let { unitPrice = 0.0, cateType, qty, isGive, averagePrice, deductionAmount9 } = cartItem;

    //商品 零售金额
    // qty 卡数量
    // unitPrice 卡价格
    let retailAmount = round(unitPrice * qty);

    // 被升级卡的最大可抵扣金额
    // 金额卡 remainBounsScore
    // 次卡 remainAmount

    const quoteCardPrice =
      quoteCard.value?.cardSubType === '101'
        ? quoteCard.value?.returnMoneyCardPrice || 0
        : quoteCard.value?.remainAmount || 0;

    // 折扣金额,用户可修改
    /**
     * 1. 如果被升级卡的剩余金额大于要升级卡的金额，则抵扣要升级卡的金额
     * 2. 反之， 抵扣金额为被升级卡的金额
     */

    deductionAmount9 ||= quoteCardPrice
      ? quoteCardPrice > retailAmount
        ? retailAmount
        : quoteCardPrice
      : 0;

    // 商品折后价
    let discountAfterAmount = round(
      isGive ? 0 : isNil(averagePrice) ? retailAmount : averagePrice * qty,
    );

    // 不限次卡的折后价逻辑
    if (!isGive && cartItem.cardSubType === '202') {
      // 卡余额
      let remainAmount = infiniteCardAmount[cartItem.busParentId];

      discountAfterAmount =
        retailAmount > remainAmount && remainAmount >= 0 ? remainAmount : retailAmount;

      remainAmount -= retailAmount;

      remainAmount = remainAmount < 0 ? 0 : remainAmount;

      /**
       * 不限次卡增加qty时，折后价最大为卡余额
       */
      if (retailAmount > infiniteCardAmount[cartItem.busParentId]) {
        discountAfterAmount = infiniteCardAmount[cartItem.busParentId];
      }

      infiniteCardAmount[cartItem.busParentId] = remainAmount;
    }
    console.log(deductionAmount9, '2222');

    deductionAmount9 = isGive || cateType === 'V' ? 0 : deductionAmount9;

    Object.assign(cartItem, {
      // 零售价
      retailAmount,
      preferentialAmount: 0,
      discountValue: null,
      moneyDeductionAmount: 0,
      moneyRetailAmount: 0,
      payableAmount: isGive || cateType === 'V' ? 0 : retailAmount - deductionAmount9,
      deductionAmount: 0,
      deductionAmount9,
      minDeductionAmount9: deductionAmount9 < 0 ? deductionAmount9 : 0,
      // 折后价
      discountAfterAmount: round(discountAfterAmount),
      // 折后价不包含优惠金额
      discountAfterAmountWithoutDeduction: discountAfterAmount,
      moneyLastAmount: 0,
    });
    console.log(cartItem, 'cartItemcartItemcartItem');
  });

  //金额卡抵扣
  cardMoneyRef.value?.forEach((cardMoneyItem) => {
    let {
      id: cardMoneyId,
      remainAmount,
      remainBounsScore,
      discountGoodsValue,
      discountServiceValue,
      discountTimesValue,
    } = cardMoneyItem;

    // 零售价
    remainAmount ||= 0;

    let lastRemainAmount = parseFloat(remainAmount || 0) + parseFloat(remainBounsScore || 0);
    console.log(remainAmount, remainBounsScore, shopCartRef.value);

    shopCartRef.value
      ?.filter((o) => !o.isGive && o.cardMoneyId === cardMoneyId)
      ?.forEach((cartItem) => {
        let { cateType, retailAmount, deductionAmount9 } = cartItem;
        deductionAmount9 ||= 0;

        //折扣(0.0-1.0)
        let discountValue =
          cateType === 'P'
            ? discountGoodsValue
            : cateType === 'S'
              ? discountServiceValue
              : cateType === 'C'
                ? discountTimesValue
                : null;
        discountValue ??= 10;
        discountValue = discountValue / 10;

        //金额卡剩余零售金额
        const moneyRetailAmount = lastRemainAmount <= 0 ? 0 : round(lastRemainAmount);

        //折后价
        let discountAfterAmount = 0.0;

        //金额卡抵扣金额
        let moneyDeductionAmount = 0.0;

        // 卡包含折扣的价值
        const originPrice = moneyRetailAmount / discountValue;

        // 卡当前的折扣金额
        const temp = originPrice - moneyRetailAmount;

        // 商品价格
        if (retailAmount > originPrice) {
          /**
           * 金额卡抵扣部分商品价格时，折后价逻辑
           *
           * m: 商品价格
           * a: 金额卡剩余金额
           * c: 折扣
           *
           * 折扣金额 = a / c - a
           * 折后价 = m - 折扣金额
           */

          discountAfterAmount = round(retailAmount - temp);
          if (discountAfterAmount < 0) {
            discountAfterAmount = 0;
          }
          moneyDeductionAmount = round(
            discountAfterAmount >= moneyRetailAmount ? moneyRetailAmount : discountAfterAmount,
          );
        } else {
          discountAfterAmount = round(
            moneyRetailAmount > 0 ? retailAmount * discountValue : retailAmount,
          );
          moneyDeductionAmount = round(
            discountAfterAmount >= moneyRetailAmount ? moneyRetailAmount : discountAfterAmount,
          );
        }

        if (moneyDeductionAmount > discountAfterAmount) {
          moneyDeductionAmount = discountAfterAmount;
        }

        //应付金额
        let payableAmount = discountAfterAmount - moneyDeductionAmount;
        lastRemainAmount -= moneyDeductionAmount;
        console.log(lastRemainAmount);
        //金额卡-剩余金额
        const moneyLastAmount = round(lastRemainAmount);

        Object.assign(cartItem, {
          retailAmount,
          discountValue,
          moneyRetailAmount,
          payableAmount: round(payableAmount - deductionAmount9),
          moneyDeductionAmount,
          discountAfterAmount: round(discountAfterAmount),
          discountAfterAmountWithoutDeduction: round(discountAfterAmount),
          moneyLastAmount,
        });
      });

    cardMoneyItem.lastRemainAmount = Math.max(0, round(lastRemainAmount));
  });

  //分摊优惠金额(升序)
  const discountAmount = cartInfoRef.value.discountAmount || 0;
  let lastDiscountAmount = cartInfoRef.value.discountAmount || 0;

  const discountTargetList =
    shopCartRef.value
      ?.filter((o) => !o.isGive && (o.cateType === 'P' || o.cateType === 'S' || o.cateType === 'C'))
      ?.map((o) => ({ cartItem: o, payableAmount: o.payableAmount ?? 0 }))
      ?.sort((a, b) => a.payableAmount - b.payableAmount) ?? [];

  let sumAmount = discountTargetList.reduce((pv, cv) => pv + (cv.payableAmount || 0), 0);
  const len = discountTargetList.length - 1;

  for (let i = 0; i <= len; i++) {
    let { cartItem } = discountTargetList[i];
    let { discountAfterAmount, payableAmount } = cartItem;

    let deductionAmount = 0;
    discountAfterAmount ||= 0;

    //计算优惠金额
    if (payableAmount > 0) {
      const tmpAmount = round(
        Math.min(payableAmount, discountAmount * (payableAmount / sumAmount)),
      );

      if (i === len) {
        deductionAmount = round(Math.min(payableAmount, tmpAmount));
      } else {
        deductionAmount = tmpAmount;
      }

      payableAmount -= deductionAmount;
    }

    discountAfterAmount -= deductionAmount;
    lastDiscountAmount -= deductionAmount;

    Object.assign(cartItem, {
      payableAmount: round(payableAmount),
      deductionAmount,
      discountAfterAmount: round(discountAfterAmount),
    });
  }
}

export function onCartQtyChange(cartItem, value, opt = { calc: false }) {
  console.log(cartItem, value, 'cartItem, value');
  const { cateType, busType } = cartItem;
  const newQty = parseInt(value || 0);

  if (cartItem.qty === newQty) {
    return;
  }

  cartItem.qty = newQty;

  let remainQty = 0;

  if (cateType === 'V') {
    if (busType === 'goods') {
      remainQty = getCardGoodsRemainQty({ ...cartItem.primitive, cartItem });
    } else if (busType === 'give') {
      remainQty = getCardGiveRemainQty({ ...cartItem.primitive, cartItem });
    }
  } else {
    cartItem.qty = newQty;
    calcPriceByCart();
    return;
  }

  if (remainQty < 0) {
    cartItem.qty = newQty - Math.abs(remainQty);
  }
  //  else if (remainQty - newQty <= 0) {
  //   cartItem.qty = remainQty;
  // }
  else {
    cartItem.qty = newQty;
  }

  if (opt.calc) {
    calcPriceByCart();
  }
}

export function onDeleteCartItem(cartItem) {
  const index = shopCartRef.value?.findIndex((o) => o.id === cartItem.id);
  if (index > -1) {
    shopCartRef.value.splice(index, 1);
    calcPriceByCart();
    deleteShopConsume(cartItem);
  }
}

export function getCardMoneyPackItemByCart(cartItem) {
  return cardMoneyRef.value?.find((o) => o.id === cartItem.cardMoneyId);
}

export function getCartQtyTotal() {
  return shopCartRef.value?.reduce((pv, cv) => pv + (cv.qty || 0), 0);
}

/**
 * 应付总额
 */
export function getCartPayableAmount() {
  // return round(shopCartRef.value?.reduce((pv, cv) => pv + (cv.disabledGive ? 0 : cv.discountAfterAmount - cv.moneyDeductionAmount || 0), 0))
  return round(
    shopCartRef.value?.reduce((pv, cv) => {
      return pv + (cv.disabledGive ? 0 : cv.discountAfterAmount - cv.moneyDeductionAmount || 0);
    }, 0),
  );
}

/**
 * 零售总额
 */
export function getCartRetailAmount() {
  return round(shopCartRef.value?.reduce((pv, cv) => pv + (cv.retailAmount || 0), 0));
}

/**
 * 优惠总额
 */
export function getCartDiscountAmount() {
  return cartInfoRef.value.discountAmount ?? 0;
}

export function getDeductionAmount() {
  return round(shopCartRef.value?.reduce((pv, cv) => pv + (cv.deductionAmount || 0), 0));
}

/**
 * 折后总额
 */
export function getCartDiscountAfterAmount() {
  return round(shopCartRef.value?.reduce((pv, cv) => pv + (cv.discountAfterAmount || 0), 0));
}

/**
 * 抵扣总额
 */
export function getCartMoneyDeductionAmount(nums) {
  console.log(nums, '98765numsnumsnums');
  return round(shopCartRef.value?.reduce((pv, cv) => pv + (cv.moneyDeductionAmount || 0), 0));
}

/**
 * 加载美容师
 */
export async function loadBeautician() {
  const result = await PAGE('/membership/getEmployeeInfoBeanPages')({
    status: 1,
    currentPage: 1,
    pageSize: 999999,
  });

  beauticianRef.value =
    result?.list
      // ?.filter((o) => o.stationCode === 'G010')
      ?.map((o) => ({
        ...o,
        value: o.id,
        label: o.realName,
      })) ?? [];
}

/**
 * 统一创建订单接口
 */
export async function createShopOrder({
  memberCode,
  cashPayCode,
  debtFee,
  totalFee,
  sourceCode,
  referer,
}) {
  const { addTime, remarks } = cartInfoRef.value;
  const discountAmount = cartInfoRef.value.discountAmount || 0;
  const { employeeCode: cashierCode } = (await getUserInfo())?.resultBean ?? {};

  //物料明细
  const orderConsumeBeanList =
    shopConsumeRef.value?.map(({ goodsSn, goodsName, csmValue, isSelected }) => ({
      goodsSn,
      goodsName,
      csmValue: csmValue || 0,
      isSelected: isSelected ? 1 : 2,
    })) ?? [];

  //商品明细
  const orderItemBeanList = [];

  shopCartRef.value?.forEach((cartItem) => {
    const { cardMoneyId, beauticianList, cateType, isGive, qty, payableAmount, deductionAmount } =
      cartItem;

    //美容师
    const employeesCodeList = [];
    beauticianList?.forEach((id) => {
      const item = beauticianRef.value?.find((o) => o.id === id);
      if (!!item) {
        employeesCodeList.push({ employeeCode: item.employeeCode, employeeName: item.realName });
      }
    });

    const item = {
      goodsQty: qty || 0,
      payablePrice: round(payableAmount || 0),
      rechargePrice: 0,
      deductionPrice: round(deductionAmount),
      employeesCodeList,
    };

    if (cateType === 'V') {
      const { cardTimesGoodsItem, memberBenefitsBeanItem, cardTimesPackItem } = cartItem.primitive;

      //TODO
      console.log('createShopOrder', cartItem.primitive);

      const cardType = cardTimesPackItem?.cardType;
      let benefitsType = !!cardTimesGoodsItem ? 'S' : memberBenefitsBeanItem?.benefitsType;

      Object.assign(item, {
        cardNo: cardTimesGoodsItem?.cardNo || memberBenefitsBeanItem?.cardNo || null,
        goodsSn:
          cardTimesGoodsItem?.batchNo ||
          cardTimesGoodsItem?.goodsSn ||
          memberBenefitsBeanItem?.benefitsSn ||
          null,
        cardBenefitsType: isGive ? 2 : 1,
        itemGoodsType:
          benefitsType === 'P' ? 1 : benefitsType === 'S' ? 2 : benefitsType === 'C' ? 3 : null,
        extensionCode: cardType === '100' ? 'banlance' : 'times',
      });
    } else {
      //正常商品
      const { proItem } = cartItem.primitive;
      const cardMoneyItem = !cardMoneyId
        ? null
        : cardMoneyRef.value?.find((o) => o.id === cardMoneyId);

      Object.assign(item, {
        cardNo: cardMoneyItem?.cardNo,
        goodsSn: proItem.batchNo || proItem.goodsSn,
        cardBenefitsType: null,
        itemGoodsType: cateType === 'P' ? 1 : cateType === 'S' ? 2 : cateType === 'C' ? 3 : null,
        extensionCode: isGive ? 'gift' : !!cardMoneyId ? 'banlance' : 'cash',
      });
    }

    orderItemBeanList.push(item);
  });

  const data = {
    cashierCode,
    cashPayCode,
    debtFee,
    totalFee,
    saleDiscount: discountAmount,
    addTime: dayjs(addTime).format('YYYY-MM-DD HH:mm:ss'),
    sourceCode,
    referer,
    remarks,
    orderConsumeBeanList,
    orderItemBeanList,
  };

  if (!!memberCode && memberCode !== '-1') {
    data.memberCode = memberCode;
  }

  console.log('createShopOrder', data);
  return await POST('/cashier/createShopOrder', data);
}

/**
 * 卡升级
 */
export async function createCardUpgradeOrder({
  memberCode,
  cashPayCode,
  debtFee,
  totalFee,
  quoteCardItem,
  sourceCode,
  referer,
  errorFn,
}) {
  const { addTime, remarks } = cartInfoRef.value;
  const discountAmount = cartInfoRef.value.discountAmount || 0;
  const { employeeCode: cashierCode } = getUserInfo()?.resultBean ?? {};

  //商品明细
  const orderItemBeanList = [];
  let newBatchNo = '';
  shopCartRef.value?.forEach((cartItem) => {
    let {
      cardMoneyId,
      beauticianList,
      cateType,
      isGive,
      qty,
      payableAmount,
      deductionAmount,
      deductionAmount9,
      discountAfterAmount,
    } = cartItem;
    deductionAmount9 ||= 0;

    //美容师
    const employeesCodeList = [];
    beauticianList?.forEach((id) => {
      const item = beauticianRef.value?.find((o) => o.id === id);
      if (!!item) {
        employeesCodeList.push({ employeeCode: item.employeeCode, employeeName: item.realName });
      }
    });

    const item = {
      goodsQty: qty || 0,
      // payableAmount
      payablePrice: round((discountAfterAmount || 0) - deductionAmount9),
      rechargePrice: 0,
      deductionPrice: round(deductionAmount9),
      employeesCodeList,
    };

    const { proItem } = cartItem.primitive;
    const cardMoneyItem = !cardMoneyId
      ? null
      : cardMoneyRef.value?.find((o) => o.id === cardMoneyId);
    newBatchNo = proItem.batchNo;
    Object.assign(item, {
      cardNo: cardMoneyItem?.cardNo,
      goodsSn: proItem.batchNo || proItem.goodsSn,
      cardBenefitsType: null,
      itemGoodsType: cateType === 'P' ? 1 : cateType === 'S' ? 2 : cateType === 'C' ? 3 : null,
      extensionCode: isGive ? 'gift' : !!cardMoneyId ? 'banlance' : 'cash',
    });

    orderItemBeanList.push(item);
  });

  if (orderItemBeanList.length < 1) {
    return errorFn?.('请选择商品');
  }

  const data = {
    cardNo: quoteCardItem.cardNo,
    batchNo: newBatchNo,
    cardType: quoteCardItem.cardType,
    employeesCodeList: orderItemBeanList[0].employeesCodeList,
    cashierCode,
    remarks,
    goodsSn: orderItemBeanList[0].goodsSn,
    memberCode,
    // 销售优惠金额
    saleDiscount: discountAmount,
    // 欠款金额
    debtFee,
    // 抵扣金额
    deductionPrice: orderItemBeanList[0].deductionPrice,
    addTime: dayjs(addTime).format('YYYY-MM-DD HH:mm:ss'),
    cashPayCode,
    sourceCode,
    referer,
    // 商品实付金额（刨去各种优惠最终计算出的金额，用于比较前后端计算是否一致）
    payablePrice: orderItemBeanList[0].payablePrice,
  };

  if (!!memberCode && memberCode !== '-1') {
    data.memberCode = memberCode;
  }

  console.log('createCardUpgradeOrder', data);
  return await POST('/cashier/createCardUpgradeOrder', data);
}

/**
 * 保存挂单
 */
export async function savePendingOrder({ memberInfo, takeId, workDate }, upgradeData = {}) {
  const { memberCode, realName: memberName, mobile: memberMobile } = memberInfo;

  const { employeeCode: cashierCode, realName: cashierName } = getUserInfo()?.resultBean ?? {};
  workDate ||= dayjs().format('YYYY-MM-DD');

  const obj = {
    shopCart: shopCartRef.value,
    shopConsume: shopConsumeRef.value,
    cartInfo: cartInfoRef.value,
  };
  if (upgradeData.isUpgrade) {
    obj.isUpgrade = true;
    obj.cardNo = upgradeData.cardNo;
    obj.memberCode = upgradeData.memberCode;
  }
  const pendingData = JSON.stringify(obj);

  const data = {
    memberCode,
    memberName,
    memberMobile,
    cashierCode,
    cashierName,
    workDate,
    pendingData,
  };

  if (!takeId) {
    await POST('/cashier/pendingOrder', data);
  } else {
    data.id = takeId;
    await PUT('/cashier/updatePendingOrder', data);
  }
}

export const emptyPendingData = '{}';
